<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2019 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2019-04-26
 * Time: 12:24
 */

namespace App\Library\User;


use App\Exceptions\ApiRequestException;
use App\Library\AuthenticatedUser;
use App\Models\Transaction;
use Illuminate\Http\Request;

trait TransactionManagers
{
    use AuthenticatedUser;

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws ApiRequestException
     */
    public function get(Request $request)
    {
        $uid = $this->user()->uid;
        $transaction_id = $request->input('transaction_id', 0);
        $transaction = Transaction::where('payer_uid', $uid)->orWhere('payee_uid', $uid)->find($transaction_id);

        if ($transaction) {
            return ajaxReturn(['transaction' => $transaction]);
        } else {
            throw new ApiRequestException(trans('transaction.transaction records do not exist'), 404);
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchget(Request $request)
    {
        $offset = $request->input('offset', 0);
        $count = $request->input('count', 20);
        $type = $request->input('type', 'all');

        $uid = $this->user()->uid;
        $query = Transaction::with(['payer', 'payee']);
        if ($type == 'income') {
            $query = $query->where('payee_uid', $uid);
        } elseif ($type == 'expend') {
            $query = $query->where('payer_uid', $uid);
        }

        $items = $query->orderByDesc('transaction_id')->offset($offset)->limit($count)->get();
        $items->each(function ($item) use ($uid){
             if ($item->payer_uid == $uid){
                 $item->income = false;
                 $item->icon = avatar($item->payee_uid);
             } else {
                 $item->income = true;
                 $item->icon = avatar($item->payer_uid);
             }
        });
        return ajaxReturn(['items' => $items]);
    }
}
